import 'package:fate_blind_box/im/ProviderChatContent.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/gzx_style.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

import '../utils/page.dart';
import '../utils/provider.dart';
import 'ChatInputBox.dart';


class ChatBottom extends StatefulWidget  {
  var groupId;
  ScrollController scrollController;


   ChatBottom(this.groupId,this.scrollController, {Key? key})
      : super(key: key);

  State<ChatBottom> createState() => _ChatBottomState();
}

class _ChatBottomState extends State<ChatBottom> with WidgetsBindingObserver {
  // 0 语音 1 键盘 2 表情
  int _inputType = 0;
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool canSend = false;
  late String centext;

 // bool get _keyboardShow => widget.providerChatContent.contentShow;

  final List<Map> _listOption = [
    {'title': '相册', 'icon': 'images/ic_dfa.png'},
    {'title': '拍照', 'icon': 'images/ic_dfa.png'},
    {'title': '视频通话', 'icon': 'images/ic_dfa.png'},
    {'title': '位置', 'icon': 'images/ic_dfa.png'},
    {'title': '红包', 'icon': 'images/ic_dfa.png'},
    {'title': '转账', 'icon': 'images/ic_dfa.png'},
    {'title': '语音输入', 'icon': 'images/ic_dfa.png'},
    {'title': '我的收藏', 'icon': 'images/ic_dfa.png'},
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _controller.addListener(() {
      setState(() {});
    });
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
      //  widget.providerChatContent.updateContentShow(true);
      }
    });
  }

  void sendMess() {
    print('---------0122----------');
    if (!canSend) {
      return;
    }
    print('---------0----------');
    // 保证在组件build的第一帧时才去触发取消清空内容
    WidgetsBinding.instance.addPostFrameCallback((_) {
     _controller.clear();
    });
    //  键盘自动收起
    //FocusScope.of(context).requestFocus(FocusNode());

    setState((){
      canSend = false;
      print('---------1----------');
      if (widget.groupId.isEmpty&&widget.groupId==null || centext.isEmpty) {
        setState(() {
          widget.scrollController.jumpTo(widget.scrollController.position.maxScrollExtent+50);

        });
        Fluttertoast.showToast(
            msg: "id和内容为空",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black,
            fontSize: 14.0
        );
        return;
      }



      var msg = EMMessage.createTxtSendMessage(
        targetId:widget.groupId,
        content: centext,
      );
      if (kDebugMode) {
        print('rx--环信id-------'+widget.groupId);
        print('rx----内容-----'+centext);
      }
      EMClient.getInstance.isConnected().then((value) =>{
        if(value){
          EMClient.getInstance.chatManager.sendMessage(msg),

        }else{
          // Provider.remove('token'),
          // Navigate.toLogin(),
        }
      });


    });
  }

  void validateInput(String test) {
    setState(() {
      canSend = test.isNotEmpty;
      centext=test;
    });
  }

  @override
  Widget build(BuildContext context) {
    print('ChatBottom------------------------build');
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(width: 1, color: Colors.black12),
        ),
      ),
      padding: const EdgeInsets.symmetric(vertical: 5),
      // height: 110.cale,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              AnimatedSwitcher(
                duration: const Duration(milliseconds: 20),
                transitionBuilder: (Widget child, Animation<double> animation) {
                  return FadeTransition(
                    opacity: animation,
                    child: child,
                  );
                },
                child: _inputType == 0
                    ? InkWell(
                  key: const ValueKey("AppIcon.audio"),
                  onTap: () {
                    print('启动音频');
                    _inputType = 1;
                   // widget.providerChatContent.updateContentShow(false);
                  },
                  child: const Padding(
                    padding:
                    EdgeInsets.only(left: 20, bottom: 10),
                    child: Icon(
                      Icons.volume_up,
                      size: 30,
                      color: Colors.black,
                    ),
                  ),
                )
                    : InkWell(
                  key: const ValueKey("AppIcon.keyboard"),
                  onTap: () {
                    _inputType = 0;
                  //  widget.providerChatContent.updateContentShow(true);
                    _focusNode.requestFocus();
                  },
                  child: const Padding(
                    padding:
                    EdgeInsets.only(left: 20, bottom: 15),
                    child: Icon(
                      Icons.keyboard,
                      size: 30,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: _inputType == 0
                    ? Padding(padding: const EdgeInsets.symmetric(horizontal: 10,
                  ),
                  child: ChatInputBox(

                    style: GZXConstant.msgbStyle,

                    onEditingComplete: () {
                      if (kDebugMode) {
                        print("onEditingComplete");
                      }
                    },
                    onSubmitted: (str) {
                      if (kDebugMode) {
                        print("onSubmitted:$str");
                      }
                    },
                    onChanged:validateInput,
                    controller: _controller,
                    focusNode: _focusNode,
                  ),
                )
                    :InkWell(
                  onTap: () {},
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 20),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(7),
                    ),
                    height: 80,
                    child: Center(
                      child: Text(
                        '按住 说话',
                        style: GZXConstant.msgsendStyle,
                      ),
                    ),
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  print('添加表情符号');
                },
                child: const Padding(
                  padding: EdgeInsets.only(bottom: 5),
                  child: Icon(
                    Icons.face,
                    size: 30,
                    color: Colors.black,
                  ),
                ),
              ),
              AnimatedSwitcher(
                duration: const Duration(milliseconds: 50),
                transitionBuilder: (Widget child, Animation<double> animation) {
                  return ScaleTransition(
                    scale: animation,
                    alignment: Alignment.centerRight,
                    child: FadeTransition(
                      opacity: animation,
                      child: child,
                    ),
                  );
                },
                child: _inputType == 0 && _controller.value.text.isNotEmpty
                    ? InkWell(
                  key: const ValueKey('发送'),
                  onTap: () {
                    sendMess();
                    print('发送');
                    _controller.clear();
                  },
                  child: Container(
                    margin: const EdgeInsets.only(
                        left: 20, right: 24, bottom: 10),
                    padding: const EdgeInsets.symmetric(
                      horizontal: 24,
                      vertical: 10,
                    ),
                    decoration: BoxDecoration(
                      color:const Color(0xff05C160),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Center(
                        child: Text(
                          '发送',
                          style: GZXConstant.msgsendStyle,
                        )),
                  ),
                )
                    : InkWell(
                  key: const ValueKey('AppIcon.add'),
                  onTap: () {
                    print('添加附件 图片视频');
                    setState(() {
                      if (_focusNode.hasFocus) {
                        _focusNode.unfocus();
                      }
                     // widget.providerChatContent.updateContentShow(true);
                      // print(
                      //     '---------${DataInheritedWidget.of(context)?.dataEnvironment.keyboardHeight}');
                      //InheritedKeyboard.of(context)?.updateKeyboard(true);
                    });
                  },
                  child: const Padding(
                    padding: EdgeInsets.only(
                        left: 10, right: 20, bottom: 5),
                    child: Icon(
                      Icons.add_circle_outlined,
                      size: 30,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
            ],
          ),
          if (false)
            Container(
              width: double.infinity,
              margin: const EdgeInsets.only(
                top: 20,
              ),
              // padding: EdgeInsets.only(bottom: 200.cale),
              decoration: const BoxDecoration(
                border: Border(
                  top: BorderSide(width: 1, color: Color(0xff55555)),
                ),
              ),
              height: 200.0,
              child: Wrap(
                runAlignment: WrapAlignment.center,
                alignment: WrapAlignment.center,
                //crossAxisAlignment: WrapCrossAlignment.center,
                spacing: 30,
                runSpacing: 30,
                children: _listOption
                    .asMap()
                    .map(
                      (key, value) => MapEntry(
                    key,
                    SizedBox(
                      width: 100,
                      height: 100,
                      child: Column(
                        children: [
                          Container(
                            width: 50,
                            height: 50,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(25),
                            ),
                            child: Image.asset(
                              value['icon'],
                              width: 50,
                              height: 50,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 10),
                            child: Text(
                              value['title'],
                              style:GZXConstant.msgbStyle,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                )
                    .values
                    .toList(),
              ),
            )
        ],
      ),
    );
  }

  ///应用尺寸改变时回调，例如旋转 键盘
  @override
  void didChangeMetrics() {
    // TODO: implement didChangeMetrics
    super.didChangeMetrics();
    if (mounted) {
      // 键盘高度
      final double viewInsetsBottom = EdgeInsets.fromWindowPadding(
          WidgetsBinding.instance.window.viewInsets,
          WidgetsBinding.instance.window.devicePixelRatio)
          .bottom;
      if (viewInsetsBottom > 0) {
       // widget.providerChatContent.updateKeyboardHeight(viewInsetsBottom);
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _focusNode.dispose();
    _controller.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
